import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/index")
public class Thymeleaf extends HttpServlet {
    //创建模板引擎
    TemplateEngine engine = new TemplateEngine();

    @Override
    public void init() throws ServletException {
        //创建模板解析器
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(this.getServletContext());
        //让模板解析器加载模板文件
        //设置前缀后缀,告诉模板引擎要加载哪些文件,以后备用
        resolver.setPrefix("/WEB-INF/template/");
        resolver.setSuffix(".html");
        resolver.setCharacterEncoding("utf-8");
        //把解析器对象加载到模板引擎中
        engine.setTemplateResolver(resolver);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String message = req.getParameter("message");
        //把从请求读出来的值与模板引擎里面的值关联起来
        WebContext webContext = new WebContext(req,resp,this.getServletContext());
        webContext.setVariable("message",message);
        //最终渲染
        engine.process("hello",webContext,resp.getWriter());
    }
}
